package domain;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.io.Writable;
import org.json.JSONException;
import org.json.JSONObject;

public class User implements Writable{
	
	private String lang;
	private String screen_name;
	   
	public String getLang() {
		return lang;
	}

	public void setLang(String lang) {
		this.lang = lang;
	}

	public String getScreen_name() {
		return screen_name;
	}

	public void setScreen_name(String screenName) {
		screen_name = screenName;
	}

	@Override
	public void readFields(DataInput arg0) throws IOException {
		parseUserFromString(arg0.toString());
		
	}

	@Override
	public void write(DataOutput arg0) throws IOException {
		arg0.writeUTF(this.toString());
		
	}
	
	@Override
	public String toString(){
		return this.lang + " - " + this.screen_name;
	}
	
	public static User parseUserFromString(String data){
		User user = new User();
		
		try {
			JSONObject myjSON = new JSONObject(data);
			if(myjSON.has("user")){
				user.setLang(myjSON.getJSONObject("user").getString("lang"));
			}else{
				user.setLang("unknown");
			}
			if(!myjSON.has("entities") || myjSON.getJSONObject("entities").getJSONArray("user_mentions").isNull(0)){
				user.setScreen_name("no_screen_name");
			}else{
				user.setScreen_name(myjSON.getJSONObject("entities").getJSONArray("user_mentions").getJSONObject(0).getString("screen_name"));
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}

}